package com.example.treasureadmin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.treasureadmin.config.AliOSSConfig;
import com.example.treasureadmin.mapper.EssayMapper;
import com.example.treasureadmin.model.EssayModel;
import com.example.treasureadmin.util.AliOSSUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.sql.Timestamp;
import java.util.List;

@Service
public class EssayService {
    @Autowired
    private EssayMapper essayMapper;
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private AliOSSConfig aliOSSConfig;
    //文章存储
    public void saveEssay(String title,String author,String content,String imageUrl) {
        Timestamp d = new Timestamp(System.currentTimeMillis());
        essayMapper.insert(new EssayModel(-1,title,author,content,0,0,d,imageUrl));
    }
    //文章删除
    public String deleteEssay(int id){
        QueryWrapper<EssayModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        EssayModel essayModel = essayMapper.selectOne(queryWrapper);
        if (essayModel == null){
            return "101";
        }
        essayMapper.delete(queryWrapper);
        return "200";
    }
    //获取文章列表
    public List<EssayModel> getAll() {
        QueryWrapper<EssayModel> queryWrapper = new QueryWrapper<>();
        return essayMapper.selectList(queryWrapper);
    }
    //按照发布时间获取文章列表
    public List<EssayModel> getByTime(String sort){
        QueryWrapper<EssayModel> queryWrapper = new QueryWrapper<>();
        if(sort.equals("desc"))
        queryWrapper.orderByDesc("create_time");
        else queryWrapper.orderByAsc("create_time");
        return essayMapper.selectList(queryWrapper);
    }
    //更新文章内容
    public void updateEssay(int id,String title,String author,String content,String imageUrl){
        UpdateWrapper<EssayModel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("title",title).set("author",author).set("content",content).set("image_url",imageUrl);
        essayMapper.update(null,updateWrapper);
    }
    //上传图片
    public String uploadImage(InputStream inputStream, String suffix) {
        String fileName = RandomStringUtils.randomAlphanumeric(32).toUpperCase();
        String essayPath = aliOSSConfig.ESSAY_PATH + fileName + suffix;
        aliOSSUtils.uploadAvatar(inputStream, essayPath);
        return aliOSSConfig.PATH+essayPath;
    }
    // 根据id获取文章
    public EssayModel getEssayById(Integer id){
        return essayMapper.selectById(id);
    }
}
